<template>
  <div>
    <el-container>
      <el-main>
        <el-container class="parent-body">
          <el-header class="content-header">
            添加/修改优惠券
            <div style="float: right">
              <el-button>
                <a @click="Return">
                  <i class="el-icon-back"></i>
                  返回
                </a>
              </el-button>
            </div>
          </el-header>
          <el-main class="info-main padding-style">
            <el-form
              :model="CouponData"
              :rules="rules"
              ref="CouponData"
              class="demo-ruleForm"
              label-width="400px"
            >
              <el-form-item label="优惠券类型：" prop="couponType">
                <el-select v-model="CouponData.disType" class="left">
                  <el-option label="注册赠券:新用户注册成功即发放到用户账户中" :value="0"></el-option>
                  <el-option label="购物赠券:购物满一定金额即发放到用户账户中(后台发货后)" :value="3"></el-option>
                  <el-option label="全场赠券:用户在优惠券首页或列表页或商品详情页或侧边栏点击领取" :value="1"></el-option>
                  <el-option label="会员赠券:同全场赠券(可限定领取的会员等级)。" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="优惠券名称:" prop="disName">
                <el-input v-model="CouponData.disName" style="width: 150px" class="left"></el-input>
              </el-form-item>
              <el-form-item label="适用平台：" prop="platform">
                <el-select v-model="CouponData.platform" class="left">
                  <el-option label="全平台" :value="1"></el-option>
                  <el-option label="PC端" :value="2"></el-option>
                  <el-option label="移动端" :value="3"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="总发行量：" prop="disNumber">
                <el-input v-model="CouponData.disNumber" style="width: 150px" class="left">
                      <i slot="suffix">0为无限制</i>
                </el-input>
              
              </el-form-item>
              <el-form-item label="面额：" prop="price">
                <el-input v-model.number="CouponData.price" style="width: 150px" class="left">
                  <i slot="suffix">元</i>
                </el-input>
              </el-form-item>
              <el-form-item label="每人限领：">{{CouponData.disLimit}}张</el-form-item>
              <el-form-item label="使用门槛:" prop="useCondition">
                <el-radio
                  v-model="isCondition"
                  label="1"
                  class="left"
                  style="margin-top: 13px"
                >
                 <span>无限制</span>  
                 </el-radio>
                <el-radio v-model="isCondition" label="2" class="left" >
                <!-- <span v-if="isCondition=='2'"> -->
                  满<el-input style="width: 100px" v-model.number="CouponData.useCondition"></el-input>元可用
                  <!-- </span> -->
                </el-radio>
              </el-form-item>
              <el-form-item label="有效期：" prop="endTime">
                  <el-date-picker
                    v-model="CouponData.endTime"
                    type="date"
                    placeholder="选择日期"
                   
                    style="width: 300px"
                  ></el-date-picker>
                    固定天数
                  <el-input style="width: 300px" v-model="CouponData.endDay">
                    <i slot="suffix" style="text-align: center">天</i>
                  </el-input>
                <!-- <el-radio v-model="CouponData.ExpirationDate" label="1" class="left">
                  日期范围
                  <el-date-picker
                    v-model="date"
                    type="date"
                    placeholder="选择日期"
                    :picker-options="pickerOptions"
                    style="width: 300px"
                  ></el-date-picker>
                </el-radio>
                <el-radio v-model="CouponData.ExpirationDate" label="2" class="left">
                  固定天数
                  <el-input style="width: 300px">
                    <i slot="suffix" style="text-align: center">天</i>
                  </el-input>
                </el-radio> -->
              </el-form-item>
                <el-form-item >以下选项会清空原有的关联,修改请慎重</el-form-item>
                <el-form-item label="可使用商品：" prop="">
                <el-radio-group v-model="canuseGood" @change="agreeChange">
                  <el-radio label="allUse">全场通用</el-radio>
                  <el-radio label="pointGood">指定商品</el-radio>
                  <el-radio label="pointClass">指定分类</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <div class="tabZujian">
                  <el-tabs v-model="canuseGood">
                    <el-tab-pane label="指定商品" name="pointGood" :key="'pointGood'" disabled>
                      <el-header>
                        <el-form-item label="* 添加商品" style="text-align: left" label-width="100px">
                          <span>
                            <el-input
                              suffix-icon="el-icon-search"
                              placeholder="商品名称/商品货号"
                              v-model="useGood.name"
                              style="width: 200px"
                            ></el-input>
                            <el-select v-model="spuId" placeholder="请选择商品">
                              <el-option
                                v-for="item in useGood.selectGood"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                              ></el-option>
                            </el-select>
                            <span style="border: 1px solid black; width:10px">
                              <i class="el-icon-plus" @click="add"></i>
                            </span>
                          </span>
                        </el-form-item>
                      </el-header>
                      <el-main>
                        <el-table :data="pointGoodData" border style="width: 100%">
                          <el-table-column prop="name" label="商品名称"></el-table-column>
                          <el-table-column prop="encode" label="货号"></el-table-column>
                          <el-table-column label="操作">
                            <template slot-scope="scope">
                              <el-button
                                size="mini"
                                @click="deleteOne(scope.$index, pointGoodData)"
                                type="text"
                              >删除</el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-main>
                      <!-- <el-footer style="height: auto">
                        <el-pagination
                          @size-change="handleSizeChange"
                          @current-change="handleCurrentChange"
                          :current-page="currentPage4"
                          :page-sizes="[10, 20, 50, 100]"
                          :page-size="500"
                          layout="total, sizes, prev, pager, next, jumper"
                          :total="400"
                        ></el-pagination>
                      </el-footer> -->
                    </el-tab-pane>
                  
                    <el-tab-pane label="指定分类" name="pointClass" :key="'pointClass'" disabled>
                      <el-header>
                        <el-form-item label="* 添加商品" style="text-align: left" label-width="100px">
                          <span>
                            <!-- <el-select v-model="getClass" placeholder="请选择分类">
                              <el-option
                                v-for="item in useGood.selectClass"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                              ></el-option>
                            </el-select> -->
                             <el-cascader
                ref="formCascader"
                v-model="getClass"
                @change="handleCascader('formCascader')"
                :props="cascader"
                popper-class="category"
                expand-trigger="hover"
                placeholder="请选择商品分类"
                clearable
              ></el-cascader>
                            <span style="border: 1px solid black; width:10px">
                              <i class="el-icon-plus" @click="addTwo"></i>
                            </span>
                          </span>
                        </el-form-item>
                      </el-header>
                      <el-main>
                        <el-table :data="pointClassData" border style="width: 100%">
                          <el-table-column prop="categoryName" label="分类名称"></el-table-column>
                          <el-table-column label="操作">
                            <template slot-scope="scope">
                              <el-button
                                size="mini"
                                @click="deleteOne(scope.$index, pointClassData)"
                                type="text"
                              >删除</el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-main>
                      <!-- <el-footer style="height: auto">
                        <el-pagination
                          @size-change="handleSizeChange"
                          @current-change="handleCurrentChange"
                          :current-page="currentPage4"
                          :page-sizes="[10, 20, 50, 100]"
                          :page-size="500"
                          layout="total, sizes, prev, pager, next, jumper"
                          :total="400"
                        ></el-pagination>
                      </el-footer> -->
                    </el-tab-pane>
                  </el-tabs>
                </div>
              </el-form-item>


              <el-form-item label="备注：" prop="disRemark">
                <el-input v-model="CouponData.disRemark" type="textarea" :rows="4" />
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
      </el-main>
      <el-footer style="text-align:center;">
        <el-button @click="Subimt" style=" color: white; background-color:steelblue">提交</el-button>
      </el-footer>
    </el-container>
  </div>
</template>
<script>
import spuApi from "@/api/goods/spu";
import classifyApi from "@/api/goods/classify";
import discountApi from "@/api/operate/discount"
import disSpuApi from "@/api/operate/disSpu"
import disClassApi from "@/api/operate/disClass"
export default {
  data() {
    return {
      canuseGood: "allUse",
      currentPage4: 1,
      date: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },

isCondition:"2",
      CouponData: {
        disId:'',
        disName: '',
        disType: '',
        platform: '',
        disNumber:'',
        disStock: '',
        price: '',
        disLimit: '',
        useCondition:'',
        endTime: "",
        endDay:'',
         disRemark:'',
      },

        rules: {
         disName: [ 
          { required: true, message:"请输入名称,使用中文谢谢", trigger: "blur" },
          { min: 3, message: "长度在 3 个字符以上", trigger: "blur" }
        ],
        disNumber: [
          {
            required: true,
            message: "只能输入正整数，输入0为无限制",
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            message: "面值只能是数值不能为负值",
            trigger: "blur"
          }
        ]
      },
      // 商品表查询数据
      useGood: {
        name: "",
        // 获取的SPU名称集合
        selectGood: [],
        // 获取分类id
        selectClass: []
      },

      // 分类练级选择器配置
      cascader: {
        checkStrictly: true,
        lazy: true,
        lazyLoad(node, resolve) {
          // const { level } = node; // = node.level
          const { value } = node;
          let parentId = value;
          if (parentId == undefined) {
            parentId = 0;
          }
          setTimeout(() => {
            classifyApi.getListById(parentId).then(result => {
              if (result.data.data.length > 0) {
                const nodes = Array.from(result.data.data).map(item => ({
                  value: item.categoryId,
                  label: item.categoryName
                  // 是否为叶子节点的标志位 (默认字段为leaf，可通过props.leaf修改)
                  // leaf: level > item.categoryLevel
                }));
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                resolve(nodes);
              } else {
                resolve();
              }
            });
          }, 1000);
        }
      },
      // 选择后获取的spuId
      spuId: null,
      // 获取到的分类
      getClass:[],




// 存放添加的数据
      pointGoodData: [],
      pointClassData: [],

// 最终提交返回的数据
      disSpu:{
        disId:'',
        spuIdList:[],
      },

       disClass:{
        disId:'',
        ids:[],
      },
    
    };
  },
  watch: {
    "useGood.name": function() {
      this.getspuName(this.useGood.name);
    },
    "isCondition":function(){

      this.CouponData.useCondition=0;
    }
  },
  methods: {
    Subimt() {
     console.log(this.CouponData);

// 添加优惠券
this.addDiscount();


    },
    agreeChange: function(val) {
      this.canuseGood = val;
    },
    deleteOne(index, rows) {
      rows.splice(index, 1);
    },

     // 分类选择
    handleCascader(target) {
      // 目的是选择之后将下拉界面收起
      this.$refs[target].toggleDropDownVisible();
    
    },
   
    add() {
      console.log(this.spuId);
      this.getspuList(this.spuId);
    },
    addTwo() {
      console.log(this.getClass);


     console.log(this.getClass[this.getClass.length-1]);

this.getClassList(this.getClass[this.getClass.length-1]);
      
      // var cate=this.arrayToString(this.getClass);

      // this.getspuListTwo(cate);
      
    },

     // 将分类拼接起来
    arrayToString(arr) {
      var arrStr = "";
      arr.forEach((item, index) => {
        if (index == 0) {
          arrStr = item;
        } else {
          arrStr += ";" + item;
        }
      });
      return arrStr;
    },


    Return() {
      this.$router.go(-1);
    },

    // 跟据名称获取到spu名
    getspuName(spuName) {

        
      spuApi.getByName(spuName).then(response => {
        console.log(response);
        this.useGood.selectGood = response.data.data;
       
      });
    },

    // 跟据id获取到spu数据
    getspuList(id) {
      // var list = {};

      spuApi.getOne(id).then(response => {
        console.log(response);

   
       this.$set(this.pointGoodData,this.pointGoodData.length,response.data.data);
        console.log(this.pointGoodData);
      
      });

   
     
    },

// // 根据分类获取spu数据
//     getspuListTwo(categoryId){

//       spuApi.getSpuByCategoryId(categoryId).then(response => {
//         console.log(response);
   
//          this.$set(this.pointClassData,this.pointClassData.length,response.data.data);
//          console.log(this.pointClassData);
//       });
//     },

getClassList(categoryId){

  classifyApi.getListAllById(categoryId).then(response=>{

console.log(response);
 this.$set(this.pointClassData,this.pointClassData.length,response.data.data);

  })

 
},

// 获取数据
intData(disId){
    discountApi.getById(disId).then(response=>{

        this.CouponData=response.data.data,

        this.disClass.disId=this.CouponData.disId;
    })
},

    // 修改优惠券
    addDiscount(){

let discount={
         disId:this.CouponData.disId,
        disName: this.CouponData.disName,
        disType: this.CouponData.disType,
        platform: this.CouponData.platform,
        disNumber:this.CouponData.disNumber,
        disStock: this.CouponData.disStock,
        price:this.CouponData.price,
        disLimit: this.CouponData.disLimit,
        useCondition:this.CouponData.useCondition,
        endTime: this.parseTime(this.CouponData.endTime),
        endDay:this.CouponData.endDay,
        disRemark:this.CouponData.disRemark

};

if(this.canuseGood=="allUse"){
    discount.allUse=1;
    this.qingkongdiSpu(this.CouponData.disId);
    this.qingkongdiClass(this.CouponData.disId);

  };


discountApi.updateOne(discount).then(response=>{

  console.log(response);

  this.getSpuList();

})
    },

    // 根据优惠券获取id
    getdisId(){

let disName=this.CouponData.disName;
      discountApi.getId(disName).then(response=>{

        console.log(response);

        this.disSpu.disId=response.data.data;

      })
    },

// 获取到需要的spu或分类集合并提交

getSpuList(){

  if(this.canuseGood=="allUse"){
    this.disSpu.spuIdList=null;
  };
  if(this.canuseGood=="pointGood"){
 this.disSpu.spuIdList=[];
this.pointGoodData.forEach(item=>{
  this.disSpu.spuIdList[this.disSpu.spuIdList.length]=item.id;
});

setTimeout(()=>{

this.getdisId();
},1000);

setTimeout(()=>{

this.addDisSpu(this.disSpu.disId,this.disSpu.spuIdList);
},2000);



  };
  if(this.canuseGood=="pointClass"){
this.disClass.ids=[];
    this.pointClassData.forEach(item=>{
    
 this.disClass.ids[this.disClass.ids.length]=item.categoryId;

     
 
});

console.log(this.pointClassData);

setTimeout(()=>{
this.jianjiaClass();

},1000)


  };
},

// 添加优惠券和spu关联表
addDisSpu(disId,spuIdList){

  disSpuApi.addOne(disId,spuIdList).then(response=>{
    console.log(response);
    this.$message(response.data.message);
  })
},





    // 时间转化
    parseTime(str) {
      if ((str + "").indexOf("-") != -1) {
        str = str.replace(new RegExp(/-/gm), "/");
      }

      let d = new Date(str);

      let newDateYear = d.getFullYear();

      let newDateMonth =
        d.getMonth() + 1 < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1;

      let newDateDay =
        d.getDate() + "" < 10 ? "0" + d.getDate() + "" : d.getDate() + "";

      return newDateYear + "-" + newDateMonth + "-" + newDateDay;
    },

    // 清空对应商品信息
    qingkongdiSpu(disId){

      disSpuApi.deleteByDisId(disId).then(response=>{
       console.log(response);

      })

    },

    qingkongdiClass(disId){

      disClassApi.deleteByDisId(disId).then(response=>{
       console.log(response);
      

      })
    },


    // 添加分类和优惠券中间表
    jianjiaClass(){

      let dto={

        disId:this.disClass.disId,
        ids:this.disClass.ids
        
      }
      disClassApi.addOne(dto.disId,dto.ids).then(response=>{

        this.$message(response.data.message);
        console.log(response);
      })
    }


    

  },

  created(){
      var disId=parseInt(this.$route.query.disId);
      this.intData(disId);
  }
};
</script>
<style scoped>
.right {
  text-align: right;
}
.left {
  text-align: left;
}
</style>
